﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BattleShips.Common;

namespace BattleShips.GameServers {
    class GameCommandParser {
        public Command Parse(string input) {
            //#<{comanda}[:{argument}]> [{mesaj}]

            Command cmd = new Command();

            if (input.StartsWith("#<")) {
                int indexOfSpace = input.IndexOf(' ');
                if (indexOfSpace == -1) {
                    indexOfSpace = input.Length - 1;
                } else {
                    cmd.Message = input.Substring(indexOfSpace).TrimEnd(';');
                }

                string fullCommand = input.Substring(1, indexOfSpace);
                if (fullCommand.EndsWith(";")) {
                    fullCommand = fullCommand.TrimEnd(';');
                } else {
                    fullCommand = fullCommand.Trim();
                }
                if (fullCommand.StartsWith("<") && fullCommand.EndsWith(">")) {
                    string[] parts = fullCommand.Substring(1, fullCommand.Length - 2).Split(':');
                    if (parts.Length == 2) {
                        cmd.CommandName = parts[0];
                        cmd.Argument = parts[1];
                    } else {
                        cmd.CommandName = parts[0];
                    }
                } else {
                    throw new ParseException("Comanda trebuie sa fie incadrata de < >.");
                }
            } else {
                throw new ParseException("Comanda trebuie sa inceapa cu #.");
            }

            return cmd;
        }
    }
}
